package com.itmck.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 太阳当空照,花儿对我笑
 * <p>
 * Create by M ChangKe 2021/8/20 14:16
 **/
@Slf4j
public class RequestUtil {

    public static String getRequestValueByKey(HttpServletRequest request, String key) {

        Map<String, Object> requestParamsMap = RequestUtil.getRequestParamsMap(request);
        return (String) Objects.requireNonNull(requestParamsMap.entrySet()
                .stream()
                .filter(e -> e.getKey().equals(key))
                .findFirst()
                .orElse(null))
                .getValue();
    }

    public static Map<String, Object> getRequestParamsMap(HttpServletRequest request) {

        HashMap<String, Object> emptyMap = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameter = parameterNames.nextElement();
            if (StrUtil.isNotBlank(parameter)) {
                String value = request.getParameter(parameter);
                if (StrUtil.isNotBlank(parameter)) {
                    emptyMap.put(parameter, value);
                }
            }
        }
        return emptyMap;
    }


    public static Map<String, Object> getRequestMap(HttpServletRequest request) {
        String method = request.getMethod();
        if (StrUtil.equalsIgnoreCase("GET", method)) {
            return RequestUtil.getRequestParamsMap(request);
        }
        return RequestUtil.getRequestJson(request);
    }

    public static Map<String, Object> getRequestJson(HttpServletRequest request) {
        Map<String, Object> emptyMap = new HashMap<>();

        try (
                ServletInputStream inputStream = request.getInputStream()
        ) {
            String body = IoUtil.read(inputStream, Charset.defaultCharset());
            if (StrUtil.isNotBlank(body)) {
                emptyMap = JSON.parseObject(body, Map.class);
            }
        } catch (IOException e) {
           log.error("IO流关闭异常",e);
        }
        return emptyMap;
    }
}